package com.itheima.web.controller.system.user;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.User;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/system/user")
public class UserServlet extends BaseServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if("list".equals(operation)){
            this.list(request,response);
        }else if("toAdd".equals(operation)){
            this.toAdd(request,response);
        }else if("save".equals(operation)){
            this.save(request, response);
        }else if("delete".equals(operation)){
            this.delete(request,response);
        }else if ("deleteMany".equals(operation)){
            this.deleteMany(request,response);
        }else if("update".equals(operation)){
            this.update(request,response);
        }else if("toUpdate".equals(operation)){
            this.toUpdate(request,response);
        }else if("search".equals(operation)){
            this.search(request,response);
        }else if("login".equals(operation)){
            this.login(request,response);
        }else if("logout".equals(operation)){
            this.logout(request,response);
        }else if("home".equals(operation)){
            this.home(request,response);
        }

    }

    private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int currentPage = 1;
        int pageSize = 5;
        String str = request.getParameter("str");
        System.out.println(str);
        if(StringUtils.isNotBlank(request.getParameter("currentPage"))){
            currentPage = Integer.parseInt(request.getParameter("currentPage"));
        }
        if(StringUtils.isNotBlank(request.getParameter("pageSize"))){
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }
        PageInfo all = userService.search(str,currentPage, pageSize);

        //将数据保存到指定的位置
        request.setAttribute("users",all);

        //记日志
//        SysLogServlet.logMethodForServlet(request);

        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-search.jsp").forward(request,response);

    }

    private void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        User user = userService.findById(id);
        request.setAttribute("user",user);

        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-role-add.jsp").forward(request,response);

    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = BeanUtil.fillBean(request, User.class);
        userService.save(user);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");
        //记日志
//        SysLogServlet.logMethodForServlet(request);
    }

    private void deleteMany(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<String> list = new ArrayList<>();
        String permissionIds = request.getParameter("permissionIds");
//        System.out.println(permissionIds);
        String[] str = permissionIds.split(",");
        for (int i = 0; i < str.length; i++) {
            list.add(str[i]);
            System.out.println(str[i]);
        }
        userService.deleteMany(list);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");

        //记日志
//        SysLogServlet.logMethodForServlet(request);

    }

    //遍历全部
    private void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //进入列表页
        //获取数据
        int currentPage = 1;
        int pageSize = 5;
        if(StringUtils.isNotBlank(request.getParameter("currentPage"))){
            currentPage = Integer.parseInt(request.getParameter("currentPage"));
        }
        if(StringUtils.isNotBlank(request.getParameter("pageSize"))){
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }
        PageInfo all = userService.findAll(currentPage, pageSize);

        //将数据保存到指定的位置
        request.setAttribute("page",all);

        //记日志
//        SysLogServlet.logMethodForServlet(request);

        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-list.jsp").forward(request,response);



    }

    //跳转到添加
    private void toAdd(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //加载所有的部门信息放入到userList
        List<User> all = userService.findAll();
        request.setAttribute("userList",all);

        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-add.jsp").forward(request,response);

        //记日志
//        SysLogServlet.logMethodForServlet(request);
    }

    //添加
    private void save(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {


        //将数据获取到，封装成一个对象
        User user = BeanUtil.fillBean(request, User.class);
        //调用业务层接口save

        //System.out.println(user);
        userService.save(user);
        //跳转回到页面list

        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");

        //记日志
//        SysLogServlet.logMethodForServlet(request);
    }
    //删除
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //将数据获取到，封装成一个对象
//        User user = BeanUtil.fillBean(request,User.class);
        String id = request.getParameter("id");
        //调用业务层接口save
//        UserService userService = new UserServiceImpl();
        userService.delete(id);

        //跳转回到页面list
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");

        //记日志
//        SysLogServlet.logMethodForServlet(request);
    }
//注销登录
    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("loginUser");
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }


    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {


        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        User user= userService.login(username,pwd);
        if(user != null) {
            request.getSession().setAttribute("loginUser", user);
            //  如果登录成功，加载该用户对应的角色对应的所有模块
            List<Module> permissionList = userService.findModuleById(user.getId());
            request.setAttribute("permissionList",permissionList);

            //  当前登录用户对应的可操作模块的所有url拼接成一个大的字符串
            StringBuffer sbf = new StringBuffer();
            for(Module m: permissionList){
                sbf.append(m.getCurl());
                sbf.append(',');
            }
            request.getSession().setAttribute("authorStr",sbf.toString());
            request.getRequestDispatcher("pages/home/main.jsp").forward(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
    private void home(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(request, response);
    }



    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }



}
